#include "CSerial.h"

CSerial::CSerial()
{
	
}
int CSerial::setInterfaceAttribs(int fd, int speed, int parity)
{
	struct termios tty;
	memset(&tty, 0, sizeof(tty));
	if(tcgetattr(fd, &tty) != 0)
	{
		perror("Serial");
		LOG(ERROR) << "Cannot get serial port attribs";
		return -1;
	}

	cfsetospeed(&tty, speed);
	cfsetispeed(&tty, speed);


        tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;     // 8-bit chars
        // disable IGNBRK for mismatched speed tests; otherwise receive break
        // as \000 chars
        tty.c_iflag &= ~IGNBRK;         // disable break processing
        tty.c_lflag = 0;                // no signaling chars, no echo,
                                        // no canonical processing
        tty.c_oflag = 0;                // no remapping, no delays
        tty.c_cc[VMIN]  = 0;            // read doesn't block
        tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

        tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl

        tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
                                        // enable reading
        tty.c_cflag &= ~(PARENB | PARODD);      // shut off parity
        tty.c_cflag |= parity;
        tty.c_cflag &= ~CSTOPB;
        tty.c_cflag &= ~CRTSCTS;

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
        {
                perror ("Serial: ");
                return -1;
        }
        return 0;
}
void CSerial::setBlocking(int fd, int block)
{
	struct termios tty;
        memset (&tty, 0, sizeof tty);
        if (tcgetattr (fd, &tty) != 0)
        {
                perror ("Serial: ");
                
                return;
        }

        tty.c_cc[VMIN]  = block ? 1 : 0;
        tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
                perror ("Serial: ");
                
}
void CSerial::writeData(int fd, std::string data)
{
	std::string dataTemp = data;
	std::cout << dataTemp.c_str() << std::endl;
        write(fd, dataTemp.c_str(), data.length());
}
int CSerial::openPort()
{
        return open(portName.c_str(), O_RDWR | O_NOCTTY);
}
std::string CSerial::readData(int fd)
{
	int n = 0;
	char buffer{};
	std::string response{};
	do
	{
		n = read(fd, &buffer, 1);
		response += buffer;
	}while(buffer != '\n' && n > 0);
	if (n < 0)
	{
	   cout << "Error reading: " << strerror(errno) << endl;
	}else if (n == 0)
	{
	    cout << "Read nothing!" << endl;
	}else
	{
		LOG(INFO) << "Got that response from: " << portName << " : " <<response;
	}
	return response;
}
CSerial::~CSerial()
{
	
}
